package com.deepglint.state;

import com.deepglint.beans.SensorReading;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.contrib.streaming.state.RocksDBStateBackend;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-22 23:46
 * 所有的容错机制
 */
public class StateTest_FaultTolerance {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 1. 状态后端配置
        env.setStateBackend(new MemoryStateBackend());
        env.setStateBackend(new FsStateBackend(""));
        env.setStateBackend(new RocksDBStateBackend(""));

        //2.检查点配
        env.enableCheckpointing(300);

        //高级配置
        env.getCheckpointConfig().setCheckpointingMode(CheckpointConfig.DEFAULT_MODE); // 保存点的级别
        env.getCheckpointConfig().setCheckpointTimeout(6000L); // 保存点超时时间
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2); // 保存点，同时最多有几个
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(100L); // 最小的间隔时间（上一个保存点完成时间---到这个保存点结束时间）
        env.getCheckpointConfig().setPreferCheckpointForRecovery(true); // 只使用检查点进行恢复，不使用手动保存点
        env.getCheckpointConfig().setTolerableCheckpointFailureNumber(2); // 允许保存点失败几次

        // 3、重启策略配置
        // 延迟重启
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,10000L)); // 重启次数，重启的间隔时间（不限制时间）
        // 失败率重启
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.minutes(10), Time.minutes(1))); // 重启次数，最大重启时间，重启时间间隔


        env.getConfig().setAutoWatermarkInterval(200);

        DataStream<String> streamSource = env.socketTextStream("192.168.150.128", 7777);

        DataStream<SensorReading> dataStream = streamSource.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], split[1], new Long(split[2]), new Double(split[3]));
        });

        SingleOutputStreamOperator<Tuple3<String, Double, Double>> mapStream = dataStream.keyBy("id").flatMap(new StateTest_keyedStateApplicationCase.MyTempWaring(10.3));

        mapStream.print();

        env.execute();
    }

    // 与上一次的温度相比，温度差超过10度，则报警
    static class MyTempWaring extends RichFlatMapFunction<SensorReading, Tuple3<String, Double, Double>> {

        // 私有属性，温度跳变阈值
        private Double threshold;

        public MyTempWaring(Double threshold) {
            this.threshold = threshold;
        }

        // 定义状态，保存上一次的值
        private ValueState<Double> lastTemp;

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTemp = getRuntimeContext().getState(new ValueStateDescriptor<Double>("last_temp", Double.class));
        }

        @Override
        public void flatMap(SensorReading value, Collector<Tuple3<String, Double, Double>> out) throws Exception {
            // 如果状态不为null，就判断两次的温度的差值
            if (lastTemp.value() != null) {
                double diff = Math.abs(value.getTemperature() - lastTemp.value());
                System.out.println(diff);
                if (diff > threshold) {
                    out.collect(new Tuple3<String, Double, Double>(value.getId(), lastTemp.value(), value.getTemperature()));
                }
            }

            lastTemp.update(value.getTemperature());
        }

        @Override
        public void close() throws Exception {
            lastTemp.clear();
        }
    }
}
